const iterTimes = 10;
const iterations = new Array(iterTimes);

// 使用立即执行的异步函数来处理 WebAssembly 模块的加载和运行
(async function() {
    try {
        // 读取 WebAssembly 模块文件
        const filePath = "/home/sjk/桌面/asc_test/build/sin_sum23.wasm";
        console.log(`Reading file from path: ${filePath}`);
        const buffer = readbuffer(filePath);

        // 创建一个持久的内存对象
        const memory = new WebAssembly.Memory({ initial: 10, maximum: 100 });

        // 定义导入对象
        const importObject = {
            env: {
                abort(message, fileName, lineNumber, columnNumber) {
                    message = __liftString(message >>> 0);
                    fileName = __liftString(fileName >>> 0);
                    lineNumber = lineNumber >>> 0;
                    columnNumber = columnNumber >>> 0;
                    throw Error(`${message} in ${fileName}:${lineNumber}:${columnNumber}`);
                },
                memory: memory,
            },
        };

        // 实例化 WebAssembly 模块
        const { instance } = await WebAssembly.instantiate(buffer, importObject);

        // 打印分割线
        console.log(`==============================`);

        // 创建一个示例数组
        const numbers = new Int32Array(100000);
        for (let i = 0; i < numbers.length; i++) {
            numbers[i] = i + 1;
        }

        // 获取 WebAssembly 内存
        const arrayBuffer = memory.buffer;

        // 手动分配内存
        const allocateArray = (length) => {
            const byteLength = length * 4; // 每个元素占用 4 字节
            const initialMemory = new Uint8Array(arrayBuffer).byteLength;
            const neededMemory = initialMemory + byteLength;
            const pageSize = 64 * 1024; // 每页 64KB
            const pagesNeeded = Math.ceil(neededMemory / pageSize);
            const currentPages = arrayBuffer.byteLength / pageSize;
            const additionalPages = pagesNeeded - currentPages;

            if (additionalPages > 0) {
                instance.exports.memory.grow(additionalPages);
            }

            const dataPtr = new Uint32Array(arrayBuffer)[0]; // 假设第一个位置是空闲内存指针
            return dataPtr;
        };

        // 分配内存
        const dataPtr = allocateArray(numbers.length);

        // 复制数据
        const arrayView = new Int32Array(arrayBuffer, dataPtr, numbers.length);
        arrayView.set(numbers);

        for (let i = 0; i < iterTimes; i++) {
            const start = Date.now();
            const result = instance.exports.calculateSinSumWithArrayRaw(dataPtr, numbers.length);
            const duration = Date.now() - start;

            // 记录每次调用的时间
            iterations[i] = duration;

            // 打印每次调用的结果和耗时
            console.log(`Iteration ${i + 1}: Result = ${result}, Time = ${duration} ms`);
        }

        // 计算平均值和标准差
        const average = iterations.reduce((sum, c) => sum + c) / iterations.length;
        const stddev = Math.sqrt(
            iterations
                .map(i => Math.pow(i - average, 2))
                .reduce((sum, c) => sum + c) / iterations.length
        );

        // 打印统计信息
        console.log(`n = ${iterations.length}`);
        console.log(`Average: ${average} ms`);
        console.log(`StdDev: ${stddev} ms`);
    } catch (error) {
        console.error(`Error loading and running WebAssembly module: ${error}`);
    }
})();